﻿using Fast.FriendlyException;
using Fast.UnifyResult.Internal;
using Fast.UnifyResult.Providers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fast.Filters
{
    public class UnifyResultFilter : IAsyncActionFilter
    {
        private readonly IUnifyResultProvider _resultProvider;

        public UnifyResultFilter(IUnifyResultProvider resultProvider)
        {
            _resultProvider = resultProvider;
        }

        /// <summary>
        /// 控制器方法执行前
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 执行控制器操作前
            var resultContext = await next();  // 执行后续操作

            // 检查是否存在异常，如果有异常，进行统一格式处理
            if (resultContext.Exception != null)
            {
                var exceptionMetadata = new ExceptionMetadata
                {
                    StatusCode = StatusCodes.Status500InternalServerError,
                    Data = null,
                    Errors = new[] { resultContext.Exception.Message }
                };
                //context.Result = _resultProvider.OnException(new ExceptionContext(resultContext.Exception, new ExceptionFilterPath()), exceptionMetadata);
            }
            else if (resultContext.Result is ObjectResult objectResult)
            {
                // 请求成功，处理返回数据
                var result = _resultProvider.OnSucceeded(resultContext, objectResult.Value);

                context.Result = result;
            }
        }
    }
}
